package com.zxz.zxzencryption.tool.encryption;


import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;


/**
 * 加密类示例 添加加密方式直接添加相关工具类
 */
public class DesEncryptionTool {
    // DES加密密钥key
    public static String key = "MIIEowIBAAKCAQEAsea7pA6kXgS4z2El8SalNVbKtuImSujodOlM6JCgCPHIkYJjcINzOJ3Mxp/afAJNAULcQ4QyVI0SOTXrqhea5vXDFTiefgNKdQG6X0Z45sNOKNxG6/9TR2cU34QqfDr7qkD0C3FlhwVswbljWpVmrnG7W0IR+I/BdRTCBBg9IWqXAwfQ9dLpnlbijlEs0IXCE7ThlADgysSWDluZ9YTfFEqwJ02G02TTXxSYhFutIeMRh1VWQvc0qIV5303lReCsyGyk3TSRN4DZcnTCLH6Hmqi/YtLxPWYa8O9LQXcfr62BEQAnMY01Un/PNicKXO4ESuC5WoaebiTgMtwXWq43HwIDAQABAoIBAQCMpmVX0ZO2GXmby6zZuboIL7RZXvbzZqzSMdlyTVWZfL8b+8Buph6kdm3940gznwYOpzPJ1WyNWHM99Bl8AumfDFLOJlN4QVXOqC0XQno3x9W1jGIuF1FaNG9WQAHu8hsigfPwUBj65RkVGGMqrM/fv19nSRc4Mz+6N00lO5ypG3DxaF0Bd2WuUayymsLu3z7eDeR4swI6GFfW3xsC/pbM0dGDJ+5RKQ7ScE0OtwPJgivxBK/BSx253SuMYltAKH8vcjnkpkiVvvHgMpzZ8f0G+sOk2LaxpDmcdoihsqvGgM32qs5JYAhoOitK3kREEo0nESwi7/GxWhXIVEyyxNUBAoGBANtkiWCLcSCt1sOoXsxB0zrHXqfipN9IB9nYOj/R5aOGoDh6vkIInVOIJNQHXkM3Y3CgUTmyu4RKfwrSyVe66IW57mJhN066C7zGrqh/NVyX7NYQl771fg3QnJMVmLmhPIlndfB2PvB9UffyaVFveo0LpMDnvZ9MlV3sFhmZrjVfAoGBAM+V3uuHrbp79hS9GW5foYOL8z1itIogeQmRVPQw9EEKYJJtqCIXv9dfVdN+Q6Yhm52bIgdoP5E8WDTCmEIng2fov7A5U+ycHLlOjyny77S79rkXbz6Z8q/9Xx2DzsJDx1vsoFtIBV5xUT6rrR7eQ/qXej5Jwry39Nxo+eQ94/JHYPVUToFN0T47NdknLC4BnarNqGOpm3oQgHDRd4mRY+nvFjM33x2+2jajYPvWoNJT0wfkpPogALYAlNJdxYeK+Mq9rWVLwlgeL8dob2cxWp/bUkkCgYAjBcUbdcOwz9M/wnu07HuChy0dsTaGi14AaD2uCUhcZNTQP6H7Roh+XL5NNWNSdx8bIx5Fo6f95/F1zVME7ke0U0dsAvAO3nPWK9PpnuwkUQYaSkLhi/WvDY9rml5a1jafYqRtpBjKSRAbkgt9dVRfVD6YsrY00anBleny7ZuCQQKBgF2LJO8rbqI49wc6frylZX9rm7I0E415BTMwUgXr1Ogkc9gBjK8FRz7TA0CrP59qjb0qK5O/rH6rJN+9YyELBs2g6Xi8b8OkH7VPWZnuA9vDMqImf4B8v2vzHctGKc49Igb6V1D1sEXmI5Q0eY31Cr27+6dmN/yWkTF/GeclZE0+";

    public static void main(String[] args) throws Exception {
        String source = "123";
        System.out.println("Excepted:" + source);

        String result = enCryptAndEncode(source);
        System.out.println("加密后:" + result);
        String source_2 = deCryptAndDecode(result);
        System.out.println("解密后:" + source_2);
        System.out.println("Actual:" + source_2);

        String isSuccess = source.equals(source_2) ? "Success" : "fail";
        System.out.println("Result:" + isSuccess);
    }
    public static String enCryptAndEncode(String content) {
        try {
            byte[] sourceBytes = enCryptAndEncode(content, key);
            return Base64.encodeBase64URLSafeString(sourceBytes);
        } catch (Exception e) {
            return content;
        }
    }

    /**
     * 加密函数
     *
     * @param content 加密的内容
     * @param strKey  密钥
     * @return 返回二进制字符数组
     * @throws Exception
     */
    public static byte[] enCryptAndEncode(String content, String strKey) throws Exception {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

        SecretKey desKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        return cipher.doFinal(content.getBytes("UTF-8"));
    }

    public static String deCryptAndDecode(String content) throws Exception {
        byte[] targetBytes = Base64.decodeBase64(content);
        return deCryptAndDecode(targetBytes, key);
    }


    /**
     * 解密函数
     *
     * @param src    加密过的二进制字符数组
     * @param strKey 密钥
     * @return
     * @throws Exception
     */
    public static String deCryptAndDecode(byte[] src, String strKey) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(strKey.getBytes()));

        SecretKey desKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, desKey);
        byte[] cByte = cipher.doFinal(src);
        return new String(cByte, "UTF-8");
    }

    // DES加密明文plaintext
    @SuppressWarnings("static-access")
    public static String encryptDES(String plaintext) {
        try {
            // 首先，DES算法要求有一个可信任的随机数源，可以通过 SecureRandom类,内置两种随机数算法，NativePRNG和SHA1PRNG
            SecureRandom random = new SecureRandom();
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(cipher.ENCRYPT_MODE, securekey, random);
            // 加密生成密文byte数组
            byte[] cipherBytes = cipher.doFinal(plaintext.getBytes());
            // 将密文byte数组转化为16进制密文
            String ciphertext = byteToHex(cipherBytes);
            return ciphertext;
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return null;
    }

    // DES解密
    @SuppressWarnings("static-access")
    public static String decryptDES(String ciphertext) {
        try {
            // DES算法要求有一个可信任的随机数源，SecureRandom内置两种随机数算法，NativePRNG和SHA1PRNG,
            // 通过new来初始化，默认来说会使用NativePRNG算法生成随机数，但是也可以配置-Djava.security参数来修改调用的算法，
            // 如果是/dev/[u]random两者之一就是NativePRNG，否则就是SHA1PRNG。
            SecureRandom random = new SecureRandom();
            // 创建一个DESKeySpec对象
            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // 将DESKeySpec对象转换成SecretKey对象
            SecretKey securekey = keyFactory.generateSecret(desKey);
            // Cipher对象实际完成解密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密匙初始化Cipher对象
            cipher.init(cipher.DECRYPT_MODE, securekey, random);
            // 将16进制密文转化为密文byte数组
            byte[] cipherBytes = hexToByte(ciphertext);
            // 真正开始解密操作
            String plaintext = new String(cipher.doFinal(cipherBytes));
            return plaintext;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将byte转化为16进制
    public static String byteToHex(byte[] bs) {
        if (0 == bs.length) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bs.length; i++) {
                String s = Integer.toHexString(bs[i] & 0xFF);
                if (1 == s.length()) {
                    sb.append("0");
                }
                sb = sb.append(s.toUpperCase());
            }
            return sb.toString();
        }
    }

    // 将16进制转化为byte
    public static byte[] hexToByte(String ciphertext) {
        byte[] cipherBytes = ciphertext.getBytes();
        if ((cipherBytes.length % 2) != 0) {
            throw new IllegalArgumentException("长度不为偶数");
        } else {
            byte[] result = new byte[cipherBytes.length / 2];
            for (int i = 0; i < cipherBytes.length; i += 2) {
                String item = new String(cipherBytes, i, 2);
                result[i / 2] = (byte) Integer.parseInt(item, 16);
            }
            return result;
        }
    }
}
